//
//  SuperViewController.m
//  News
//
//  Created by xalo on 16/3/2.
//  Copyright © 2016年 News. All rights reserved.
//

#import "SuperViewController.h"
#import "VideoViewCell.h"

#import "HTTPHelper.h"
#import "VideoModel.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

#import <MJRefresh.h>
#import "VideoDetailViewController.h"
#import "UITableViewController+RemoveAVPlayer.h"
#import "FMDatabase+Database.h"
#import <MBProgressHUD.h>
#import <Reachability.h>
#import "ContainerViewController.h"

@interface SuperViewController ()<ContainerViewControllerDelegate>
@property (nonatomic,strong) AVPlayerViewController *AVPlayer;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) VideoModel *videoModel;
@property (nonatomic,assign) CGRect videoframe;
@property (nonatomic,strong) ContainerViewController *container;


@property (nonatomic,strong) UIActivityIndicatorView *activityView;

@property (nonatomic,strong) NSMutableArray *videoArray;


@end

@implementation SuperViewController


//执行代理方法;
-(void)refreshData
{

    [self pullDownToRefreshData];


}



//页面消失时移除播放器
-(void)viewDidDisappear:(BOOL)animated
{
    [self.AVPlayer.view removeFromSuperview];
    self.AVPlayer = nil;
}



//懒加载数组
-(NSMutableArray *)videoArray
{
    
    if (!_videoArray) {
        
        _videoArray = [NSMutableArray array];
    }
    return _videoArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
     self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    NSLog(@"%@",self.channel);
    
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    
    [self setData];
    //
    
    self.container = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"container"];
    self.container.clikDelegeta = self;
    
    
    
 
    [self pullDownToRefreshData];
    
    [self pullUpToRefreshData];
    
    [self.AVPlayer.view layoutIfNeeded];
    
    
   
    
    
    
}



-(void)setData
{

    if (![self connectState]) {
        [self getDateBydataBase];
        
        [self.tableView reloadData];
        
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];


        
    }else{
        [self setNetWorkingData];
    
    }
    
    
}


//判断网络状态
-(BOOL)connectState
{

    BOOL state;
     Reachability *ablity = [Reachability reachabilityForInternetConnection];
    

    if (ablity == NotReachable) {
        
        state = NO;
    }else{
    
        state = YES;
    }
    
    return state;
}


-(NSArray *)getDateBydataBase
{

   NSArray *array = [[FMDatabase shareManager] selectNewsModelArrayWithChannel:self.channel times:0];
    
    
    for (NSDictionary *dict in array) {
        
        
        VideoModel *model = [[VideoModel alloc]init];
        
        NSArray *array = [dict allKeys];
        
        for (NSString *string in array) {
            if ([string isEqualToString:@"video_info"]) {
                
                NSDictionary *dict1 = dict[@"video_info"];
                [model setValuesForKeysWithDictionary:dict1];
            }
        }
        
        [model setValuesForKeysWithDictionary:dict];
        [self.videoArray addObject:model];
        
    }

    
    return array;

}


-(void)setNetWorkingData
{

    
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];

    [[HTTPHelper sharedManger] fetchVideo_videoDataWithchannel:self.channel videoArray:self.videoArray block:^{
        
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        
    } reblock:^{
        
        
        if ([self getDateBydataBase] !=nil) {
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            
        }else{
        
            [self performSelector:@selector(dataLoadError) withObject:nil afterDelay:5.0];
        
        }
        
    }successBlock:^(id  _Nullable responseObject) {
        //nothing;
        
    } ];
    
}


-(void)dataLoadError
{

    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loaderror.gif"]];
    imageView.frame = CGRectMake(0, 0, 300,300);
    
    imageView.center = self.tableView.center;
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.frame = CGRectMake(0, 0, 300, 30);
    titleLabel.text = @"网络加载错误...";
    titleLabel.center = imageView.center;
    
   
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [imageView addSubview:titleLabel];
    
    self.tableView.backgroundView = imageView;
    [MBProgressHUD hideHUDForView:self.tableView animated:YES];

}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;

}



#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.videoArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    VideoModel *videoModel = self.videoArray[indexPath.row];
    
    [cell setCountentViewWithModel:videoModel];
    
    self.videoframe = cell.backView.frame;
    
    
    cell.playButton.tag = indexPath.row;
    cell.infoButton.tag = indexPath.row;
    
    [cell.playButton addTarget:self action:@selector(playButton:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [cell.infoButton addTarget:self action:@selector(turnToDetailView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    return cell;
}



-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.AVPlayer.player.rate == 0 ||self.AVPlayer.player.rate == 1.0) {
        
        [self.AVPlayer.view removeFromSuperview];
        self.AVPlayer = nil;
        
    }
    
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    CGFloat height = [UIScreen mainScreen].bounds.size.width*3/4;
    
    return height;

}



-(void)turnToDetailView:(UIButton *)button
{
    VideoModel *videoModel = self.videoArray[button.tag];
    
    
    
    
    VideoDetailViewController *detailVC = [[UIStoryboard storyboardWithName:@"Video" bundle:nil]instantiateViewControllerWithIdentifier:@"detail"];
    detailVC.videoModel = videoModel;
    
   
    [self presentViewController:detailVC animated:YES completion:nil];

}






-(void)playButton:(UIButton *)button
{
    if (_AVPlayer) {
        
        [self.AVPlayer.view removeFromSuperview];
        self.AVPlayer = nil;
        
    }
    
    [self preparePlayWithPlayeritemWithindex:button.tag];
    [button addSubview:self.AVPlayer.view];
    
    [self.AVPlayer.player play];
    
    
    
}

-(UIActivityIndicatorView *)activityView
{
    if (_activityView) {
        
        _activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
    }
    return _activityView;
    
}


-(AVPlayerViewController *)AVPlayer
{
    if (!_AVPlayer) {
        
        _AVPlayer = [[AVPlayerViewController alloc]init];
    }
    
    return _AVPlayer;
    
}


-(void)preparePlayWithPlayeritemWithindex:(NSInteger)index
{
    
    VideoModel *model = self.videoArray[index];
    self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:model.url]];
    
    self.AVPlayer.player = [[AVPlayer alloc]init];
    [self.AVPlayer.player replaceCurrentItemWithPlayerItem:self.playerItem];
    self.AVPlayer.view.frame = self.videoframe;
    
    
    
    [self addNotification];
    
}




-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerStateChange) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    
}


-(void)avPlayerStateChange
{
    [self.AVPlayer.view removeFromSuperview];
    self.AVPlayer = nil;
    
}






-(void)pullDownToRefreshData
{
     self.times = 1;
        
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
     
        if ([self connectState]) {
            
            
            [[HTTPHelper sharedManger] fetchVideo_videoDataWithchannel:self.channel videoArray:self.videoArray block:^{
                
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                
                
            } reblock:^{
                //加载失败
                
                [self showAlertView];
                [self getDateBydataBase];
                
                [self.tableView.mj_header endRefreshing];
                
            } successBlock:^(id  _Nullable responseObject) {
                
                [self.videoArray removeAllObjects];
                
                
            }];
        }else{
        
            [self showAlertView];
        [self.tableView.mj_header endRefreshing];
        }
        
    }];
    
}

//没网是弹出警示框
-(void)showAlertView
{

    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"网络提示" message:@"没有网络,小编君也没办法" preferredStyle:(UIAlertControllerStyleAlert)];
    [self presentViewController:alert animated:YES completion:nil];
    
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:1.0];

}


-(void)dismiss {

    [self dismissViewControllerAnimated:YES completion:nil];

}


-(void)pullUpToRefreshData
{

    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
       
        if ([self connectState]) {
            
            [[HTTPHelper sharedManger] pullUpRefreshDataWithChannel:self.channel times:self.times videoArray:self.videoArray block:^{
                
                self.times++;
                
                
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
                
                
            } reblock:^{
                [self showAlertView];
                
                [self.tableView.mj_footer endRefreshing];
                
            }];

            
            
        }else{
            
            [self showAlertView];
            [self.tableView.mj_header endRefreshing];
        }
        

        
        
    }];
    
 
    
}


-(void)removeAVPlayer
{
    [self.AVPlayer.view removeFromSuperview];
    self.AVPlayer = nil;
    
}



- (void)statusBarOrientationChange:(NSNotification *)notification
{
//    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
//    if (orientation == UIInterfaceOrientationLandscapeRight||orientation == UIInterfaceOrientationLandscapeLeft) {
//        self.tabBarController.tabBar.hidden= YES;
//        self.navigationController.navigationBarHidden = YES;
//        
        [self.tableView reloadData];
    
//
//    }else{
//    
//        self.tabBarController.tabBar.hidden= NO;
//        self.navigationController.navigationBarHidden = NO;
//
//    }

}









@end
